/**
 * create by young (young2f@outlook.com) on 2020/9/16
 */


'use strict';
import React from 'react';
import {Button, Form, Input, notification, DatePicker, Select, Table} from 'antd';

import {FormField, ModalFooter, SearchForm} from 'antd-extra';
import FormBase from '../../../components/Base/FormBase';
import {connect} from "dva";
import moment from 'moment';
import 'moment/locale/zh-cn';

import ViewTitle from "../../../components/ViewTitle";
import {title} from "mockjs/src/mock/random/text";
import _ from "lodash";
import styles from "../../index.less";

const {RangePicker} = DatePicker;

moment.locale('zh-cn');

@Form.create()
@connect(({
            tenant,
            global,
            finance, dict
          }) => ({...tenant, ...finance, ...global, ...dict}))
export default class ModalSelectProcureMaterials extends FormBase {
  constructor(props) {
    super(props);
    this.state = {tagColor: undefined, selectedRowKeys: []};
  }

  componentDidMount() {
    const payload = this.props.form.getFieldsValue();
    _.map(payload, (value, key) => {
      if (value === '') {
        payload[key] = undefined;
      }
    });
    this.props.dispatch({
      type: 'dict/findMany',
      payload: {type: 'division'}
    });

    this.props.dispatch({
      type:'finance/findInvoiceProcureMany',
      payload
    });
  }

  renderFoot = () => {
    const {foot, value, procureInvoices = [], callback, modalRef, form} = this.props;

    if (foot) {
      return foot(value, modalRef);
    } else {
      return (
        <ModalFooter>
          <Button type="primary" onClick={() => {
            form.validateFields((err, values) => {

              if (err) {
                const {code} = err;
                const {errors} = code;
                errors.forEach(item => {
                  notification.error(item);
                });
                return;
              }
              const {selectedRowKeys = []} = this.state;
              const prods = [];
              _.map(selectedRowKeys, (value, key) => {
                const prod = _.find(procureInvoices, item => {
                  return item.pmLotId === value;
                });
                prods.push(prod);
              });
              callback(prods);
              modalRef.close();
            });

          }}>确定</Button>
          <Button onClick={() => {
            modalRef.close();
          }}>取消</Button>
        </ModalFooter>
      );
    }
  };

  materialCols(){
    return[
      {title:'采购单编码', dataIndex: 'procureOrderCode', key: 'procureOrderCode'},
      {title:'物料名称', dataIndex: 'name', key: 'name'},
      {title:'物料编码', dataIndex: 'code', key: 'code'},
      {title:'物料形态', dataIndex: 'subcategory', key: 'subcategory'},
      {title:'物料规格', dataIndex: 'spec', key: 'spec'},
      {title:'物料类型', dataIndex: 'type', key: 'type'},
      {title:'物料编号', dataIndex: 'number', key: 'number'},
      {title:'单价', dataIndex: 'price', key: 'price'},
      {title:'数量', dataIndex: 'count', key: 'count'},
      {title:'用途', dataIndex: 'target', key: 'target'},
      {title:'供应商', dataIndex: 'vendor', key: 'vendor'},
      {title:'采购类型', dataIndex: 'materialType', key: 'materialType'},
      {title:'采购公司', dataIndex: 'division', key: 'division'},
      {title:'采购日期', dataIndex: 'createdTs', key: 'createdTs',fixed:'right',render: value => {return <div>{moment(value).format('YYYY-MM-DD')}</div>}},
    ]
  }

  onSelectChange = selectedRowKeys => {
    this.setState({selectedRowKeys});
  };

  render() {
    const {form, cols, title, procureInvoices = [], divisionDict = [], selectedProds} = this.props;
    const {selectedRowKeys} = this.state;
    const rowSelection = {
      type: 'checkbox',
      selectedRowKeys,
      onChange: this.onSelectChange,
      getCheckboxProps: record => ({
        disabled: _.find(selectedProds, item => {
          return item.pmLotId === record.pmLotId;
        })
      })
    };
    const onSelectRow = (record) => {
      const {pmLotId} = record;
      const temp = _.find(selectedRowKeys, item => {
        return item === pmLotId;
      });
      if (temp) {
        _.remove(selectedRowKeys, item => item === pmLotId);
      } else {
        selectedRowKeys.push(record.pmLotId);
      }
      this.onSelectChange(selectedRowKeys);
    };
    return (
      <div>
        <ViewTitle
          title={`采购物料列表`}
          level={1}
        ></ViewTitle>
        <SearchForm
          style={{marginLeft: '6px', marginRight: '6px'}}
          onSearch={() => {
            this.state.current = 1;
            this.componentDidMount();
          }}
          onReset={this.handleReset}
          cols={3}
          min={6}
          expandText="展开"
          form={form}
        >
          {[
            <FormField
              label="供应商名称"
              name="vendor"
              key={1}
            >
              <Input allowClear placeholder={`请输入`}/>
            </FormField>,
            <FormField
              label={'采购公司'}
              name={`division`}
              key={`division`}
            >
              <Select allowClear placeholder={`请输入采购公司`}>{this.getDivision(divisionDict)}</Select>
            </FormField>,
            <FormField
              label={`统计时间`}
              name="createdTs"
              key={3}
              initialValue={[this.getSearchStart1Months(), this.getDefaultSearchEndDate()]}
            >
              <RangePicker allowClear={true}
                // style={{ width: '150%' }}
              />
            </FormField>
          ]}
        </SearchForm>
        <Table
          className={styles.antTable}
          bordered={true}
          rowSelection={rowSelection}
          rowKey={record => record.pmLotId}
          onRow={(record) => ({
            onClick: () => onSelectRow(record)
          })}
          columns={this.materialCols()}
          dataSource={procureInvoices}
          scroll={{x: true}}
          pagination={{
            current: this.state.current,
            total: this.state.total,
            showSizeChanger: true,
            onChange: page => {
              this.state.current = page;
              this.componentDidMount();
            },
            onShowSizeChange: (current, pageSize) => {
              this.state.current = 1;
              this.state.pageSize = pageSize;
              this.componentDidMount();
            }
          }}
          //  scroll={{ x: 1300 }}
        ></Table>
        {this.renderFoot()}
      </div>
    );
  }
}

